import React, { useEffect, useMemo, useState } from 'react';
import styles from './index.less';
import { Button, Checkbox, Dropdown, Space, Tooltip } from 'antd';
import _ from 'lodash';
import { PlusOutlined, QuestionCircleOutlined } from '#/utils/antdIcons';

const DropEl = ({ options = [], onChange, type, onDelete, disableDelete = false }) => {
  const [startIndex, setStart] = useState(null);

  const onDragEnd = (e) => {
    e.preventDefault();
    setStart(null);
  };
  const onDragEnter = (e, hoverIndex) => {
    if (startIndex === hoverIndex) {
      return;
    }
    setStart(hoverIndex);
    changePosition(startIndex, hoverIndex);
  };

  const changePosition = (dragIndex, hoverIndex) => {
    if (dragIndex || dragIndex === 0) {
      const data = _.cloneDeep(options);
      const temp = data[dragIndex];
      data.splice(dragIndex, 1);
      data.splice(hoverIndex, 0, temp);
      onChange(data, type);
    }
  };

  const onDragStart = (e, index) => {
    if (startIndex) {
      return;
    }
    setStart(index);
  };

  const onDragOver = (e) => {
    e.preventDefault();
  };

  const onDragLeave = (e) => {
    e.preventDefault();
  };

  return (
    <>
      {options.map((i, k) => (
        <div
          draggable
          onDragEnd={(e) => {
            onDragEnd(e);
          }}
          onDragEnter={(e) => {
            onDragEnter(e, k);
          }}
          onDragStart={(e) => {
            onDragStart(e, k);
          }}
          onDragOver={(e) => {
            onDragOver(e);
          }}
          onDragLeave={(e) => {
            onDragLeave(e);
          }}
          key={i.value}
          className={styles.btn_sort}
        >
          <Button className={`${styles.btn} ${startIndex === k && styles.drag}`}>{i.label}</Button>
          {!(options.length <= 1 || disableDelete) && (
            <svg
              onClick={() => {
                onDelete(k, type);
              }}
              className={styles.delete}
              xmlns="http://www.w3.org/2000/svg"
              width="12"
              height="12"
              viewBox="0 0 12 12"
              fill="none"
            >
              <circle cx="6" cy="6" r="6" fill="#FD4F43" />
              <rect
                x="3.10767"
                y="5.35693"
                width="5.78466"
                height="1.28571"
                rx="0.642857"
                fill="white"
              />
            </svg>
          )}
        </div>
      ))}
    </>
  );
};

const AddBtn = ({ select = [], options = [], setSelect }) => {
  const [temp, setTemp] = useState([]);

  const [selectData, setSelectData] = useState([]);

  useEffect(() => {
    const arr = options.filter((i) => !select.some((s) => s.value === i.value));
    setTemp(arr);
  }, [select]);
  const visibleChange = (visible) => {
    if (selectData.length) {
      !visible &&
        setSelect([...select, ...options.filter((i) => selectData.some((s) => s === i.value))]);
      setSelectData([]);
    }
  };

  const checkBoxOnChange = (e, value) => {
    e.target.checked
      ? setSelectData([...selectData, value])
      : setSelectData(selectData.filter((t) => t !== value));
  };

  return (
    <Dropdown
      overlay={
        <div className={styles.checkbox_group}>
          {temp.map((t) => (
            <div
              key={t.value}
              onClick={(e) => {
                e.stopPropagation();
              }}
            >
              <Checkbox
                checked={selectData.includes(t.value)}
                onChange={(e) => {
                  checkBoxOnChange(e, t.value);
                }}
              >
                {t.label}
              </Checkbox>
            </div>
          ))}
        </div>
      }
      onVisibleChange={visibleChange}
      disabled={!temp.length}
      placement="bottomLeft"
      trigger={['click']}
    >
      <Button
        style={
          temp.length
            ? {
                background: 'var(--ant-cus-bg2_a10)',
                border: '1px solid var(--ant-cus-bg2_a50)',
                color: 'var(--ant-cus-bg2)',
              }
            : null /*  {
                background: 'var(--font-a30)',
                border: '1px solid var(--ant-cus-bg2_a50)',
                color: 'var(--font-a30)',
              } */
        }
        className={styles.add_btn}
        disabled={!temp.length}
      >
        <PlusOutlined />
      </Button>
    </Dropdown>
  );
};

export const DimensionalDoubleSort = ({
  onClick,
  leftOptions = [],
  rightOptions = [],
  leftAggregate = [],
  rightAggregate = [],
}) => {
  const [allOptions, setAllOptions] = useState([]);

  const [leftSelect, setLeftSelect] = useState([]);

  const [rightSelect, setRightSelect] = useState([]);

  useEffect(() => {
    const arr = [];
    leftOptions?.forEach((i) => {
      arr.push(i.label);
    });
    rightOptions?.forEach((i) => {
      arr.push(i.label);
    });
    setAllOptions(arr);
    setRightSelect(rightAggregate);
    setLeftSelect(leftAggregate);
  }, [rightAggregate, leftAggregate, leftOptions, rightOptions]);

  const changeSelect = (v, type) => {
    if (type === 'right') {
      setRightSelect(v);
    } else if (type === 'left') {
      setLeftSelect(v);
    }
  };

  const deleteSelect = (index, type) => {
    let arr = type === 'right' ? [...rightSelect] : [...leftSelect];
    arr.splice(index, 1);
    if (type === 'right') {
      setRightSelect(arr);
    } else if (type === 'left') {
      setLeftSelect(arr);
    }
  };

  const handleAggregate = () => {
    onClick(leftSelect, rightSelect);
  };

  return (
    <div className={styles.body}>
      <div className={styles.head}>
        <div className={styles.title}>
          聚合维度选择
          <Tooltip
            title={`功能支持的数据聚合维度包括“${allOptions.join(
              '”、“',
            )}”，您可通过增减维度数量、调整维度顺序来控制数据聚合，获得想要的效果。`}
          >
            <QuestionCircleOutlined className={styles.tip_icon} />
          </Tooltip>
        </div>
        <div className={styles.title}>
          算法模型说明
          <Tooltip
            title={
              <div style={{ width: 260 }}>
                <div>RMSE 全国电价上下限电价预测准确率</div>
                <div>PSAE 分时段电价预测准确率</div>
              </div>
            }
          >
            <QuestionCircleOutlined className={styles.tip_icon} />
          </Tooltip>
        </div>
        <Button type={'primary'} onClick={handleAggregate}>
          聚合
        </Button>
      </div>
      <div className={styles.content}>
        <div className={styles.left_content}>
          <div className={styles.drop_line}>
            <div className={styles.label}>维度(行):</div>
            {useMemo(
              () => (
                <DropEl
                  options={leftSelect}
                  onChange={changeSelect}
                  onDelete={deleteSelect}
                  type={'left'}
                />
              ),
              [leftSelect],
            )}
            {useMemo(
              () => (
                <AddBtn select={leftSelect} options={leftOptions} setSelect={setLeftSelect} />
              ),
              [leftSelect, leftOptions],
            )}
          </div>
          <div className={styles.drop_line} style={{ marginLeft: 20 }}>
            <div className={styles.label}>维度(列):</div>
            {useMemo(
              () => (
                <DropEl
                  disableDelete={true}
                  options={rightSelect}
                  onChange={changeSelect}
                  onDelete={deleteSelect}
                  type={'right'}
                />
              ),
              [rightSelect],
            )}
            {useMemo(
              () => (
                <AddBtn select={rightSelect} options={rightOptions} setSelect={setRightSelect} />
              ),
              [rightSelect, rightOptions],
            )}
          </div>
        </div>
      </div>
    </div>
  );
};
